use async_dup::{Arc, Mutex};
use iced::{button, Button, Column, Element, Sandbox, Text};
use smol::Timer;
use std::time::Duration;

#[derive(Default)]
pub(crate) struct Counter {
    value: Arc<Mutex<i32>>,
    increment_button: button::State,
    decrement_button: button::State,
}

#[derive(Debug, Clone, Copy)]
pub(crate) enum Message {
    IncrementPressed,
    DecrementPressed,
}

impl Sandbox for Counter {
    type Message = Message;

    fn new() -> Self {
        Self::default()
    }

    fn title(&self) -> String {
        String::from("A simple counter")
    }

    fn update(&mut self, message: Message) {
        let a = self.value.clone();
        match message {
            Message::IncrementPressed => {
                *self.value.lock() += 1;
                smol::spawn(async move {
                    Timer::after(Duration::from_secs(10)).await;
                    *a.lock() = 100;
                })
                .detach();
            }
            Message::DecrementPressed => {
                *self.value.lock() -= 1;
            }
        }
    }

    fn view(&mut self) -> Element<Message> {
        Column::new()
            .padding(20)
            .push(
                Button::new(&mut self.increment_button, Text::new("Increment"))
                    .on_press(Message::IncrementPressed),
            )
            .push(Text::new(self.value.lock().to_string()).size(50))
            .push(
                Button::new(&mut self.decrement_button, Text::new("Decrement"))
                    .on_press(Message::DecrementPressed),
            )
            .into()
    }
}
